package com.rabbiter.fm.controller;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/click")
public class ClickController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 记录商品点击次数
    @PostMapping("/{userId}/{itemId}")
    public String recordClick(@PathVariable Long userId, @PathVariable Long itemId) {
        // 增加的 SQL 语句，将 sh_user 表中该用户对应的 interests 字段设置为空
        jdbcTemplate.update(
                "UPDATE sh_user SET interests = NULL WHERE id = ?",
                userId
        );

        // 使用 queryForList 查询是否已有记录
        List<Map<String, Object>> result = jdbcTemplate.queryForList(
                "SELECT click_count FROM user_item_clicks WHERE user_id = ? AND item_id = ?",
                userId, itemId
        );

        if (!result.isEmpty()) {
            // 如果已有记录，则更新点击次数
            jdbcTemplate.update(
                    "UPDATE user_item_clicks SET click_count = click_count + 1 WHERE user_id = ? AND item_id = ?",
                    userId, itemId
            );
            return "Click count updated";
        } else {
            // 如果没有记录，则插入新的记录
            jdbcTemplate.update(
                    "INSERT INTO user_item_clicks (user_id, item_id, click_count) VALUES (?, ?, ?)",
                    userId, itemId, 1
            );
            return "Click record created";
        }
    }
}
